<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:include value="/WEB-INF/content/common/header.jsp" />
<title><s:text name="global.application.title" /> - <s:text	name="global.title.input" /></title>
</head>
<body>
	<div class="container-fluid">
		<div class="row-fluid">
			<s:include value="/WEB-INF/content/common/title-head.jsp" />
		</div>
		<div class="row-fluid">
			<div class="container-fluid well">
				<div class="span2">
					<s:url action="view" namespace="/menuItems" var="menuItems" />
					<s:a href="%{#menuItems}" cssClass="btn boxButton btn-custom" style="margin-bottom:10px;">
						<s:text name="menu.return" />
					</s:a>
				</div>
				<div class="span10">
					<div class="input-prepend">
						<span class="add-on" style="margin-right: -4px;">
							<s:text name="implimentation.time" />
						</span> 
						<span class="add-on" style="-webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; margin-right: -5px;">
							<s:checkbox name="chk" id="enableTime" />
						</span>
					</div>
					<div class="input-append input-prepend">
						<div class=" bootstrap-timepicker" style="display: inline-block;">
							<s:textfield id="timepicker" name="time" cssClass="input-small" />
							<span class="add-on"> <i class="icon-time"></i></span>
							<button class="btn btn-custom" id="btnCurrentTime">
								<s:text name="btn.current.time" />
							</button>
						</div>
					</div>
					<div class="hidden">
						<s:url action="completeSession" namespace="/home" var="completeSession" />
						<s:a href="%{#completeSession}" id='completeSession'/>
					</div>
						
					<button class="btn btn-custom pull-right" id="btnComplete">
						<s:text name="btn.complete.session" />
					</button>
				</div>
			</div>
		</div>
		<div class="row-fluid">
			<div class="wellwhite" id="data">
				<div id="sliderTabs">
					<!-- Unordered list representing the tabs -->
					<ul class="nav nav-tabs" id="menuTab">
						<s:iterator value="menuItemList" status="rowIndex">
							<li>	
								<a href="#tab<s:property value='#rowIndex.index'/>"><s:property	value="groupName" /></a>
							</li>
						</s:iterator>
					</ul>
				</div>
				<div class="tab-content">
					<s:iterator value="menuItemList" status="rowIndex">
						<div class="tab-pane" id="tab<s:property value='#rowIndex.index'/>">
						<input class="hidden" id="origplannedTimetab<s:property value='#rowIndex.index'/>" value = '<s:date name="%{plannedTime}" format="HH:mm"/>'/>
							<s:form namespace="/input" action="save" theme="simple">
							<input class="hidden" id="plannedTimetab<s:property value='#rowIndex.index'/>" name="plannedTime"/>
								<s:hidden name="inputGroup" value="%{groupName}" />
								<s:hidden name="executionDateHidden" id="executionDate" />
								<div class="table-responsive">
									<table class="table table-bordered">
										<s:iterator value="%{inputItemList.get(groupId)}" status="rowIndex">
											<tr>
												<td style="vertical-align: middle" class="span2">
													<s:property	value="itemGroupName" /></td>
												<td style="vertical-align: middle" class="record-items">
													<s:if test="%{itemType.equals('SELECT')}">
														<s:radio name="ansRad" list="recordItemState.itemList"
															labelposition="inline" value="recordItemState.selectedList" />
														<s:hidden name="ansRadHidden" value="%{itemGroupName}" />

													</s:if> <s:elseif test="%{itemType.equals('CHECK')}">
														<s:checkboxlist name="ansChk"
															list="recordItemState.itemList"
															value="recordItemState.selectedList"/>
														<s:hidden name="ansChkHidden" value="%{itemGroupName}" />

													</s:elseif> <s:elseif test="%{itemType.equals('INTEGER')}">
														<%-- <s:textfield name="ansTxtInt"
															cssClass="%{itemType} txt_input"
															cssStyle="text-align:right"
															value="%{recordItemState.selectedList}" /> --%>
															
															<div class="bootstrap-timepicker-widget open vitaltable">
																<table class="table table-bordered span2">
																    <tbody>
																        <tr>
																            <td><a  class="valuechanger" href="#" onclick="decrementValue('#vital<s:property value='#rowIndex.index'/>')"><i class="icon-chevron-left"></i></a>
																            </td>
																       
																            <td>
																                <input name="ansTxtInt" id="vital<s:property value='#rowIndex.index'/>" class="bootstrap-timepicker-hour INTEGER txt_input vitalinputs" readonly style="margin-top:3px; width:45px; background-color: #ffffff;" maxlength="3" type="text">
																            </td>
															
																            <td><a  class="valuechanger" href="#" onclick="incrementValue('#vital<s:property value='#rowIndex.index'/>')"><i class="icon-chevron-right"></i></a>
																            </td>
																            
																        </tr>
																    </tbody>
																</table>
															</div>
															<td>
																<a onclick="getDefaultValue('#vital<s:property value='#rowIndex.index'/>')">
																	<img src="../theme/img/setdefault.png" class="btn vitalbtn valuechanger">
																</a>
															</td>
															
															
															
															
															
														<s:hidden name="ansTxtIntHidden" value="%{itemGroupName}" />

													</s:elseif> <s:elseif test="%{itemType.equals('DOUBLE')}">
														<%-- <s:textfield name="ansTxtDouble"
															cssClass="%{itemType} txt_input"
															cssStyle="text-align:right"
															value="%{recordItemState.selectedList}" /> --%>
															
															<div class="bootstrap-timepicker-widget open vitaltable">
																<table class="table table-bordered span2" >
																    <tbody>
																        <tr>
																            <td><a class="valuechanger" href="#" onclick="decrementValue('#vital<s:property value='#rowIndex.index'/>')"><i class="icon-chevron-left"></i></a>
																            </td>
																       
																            <td>
																                <input name="ansTxtDouble" id="vital<s:property value='#rowIndex.index'/>" class="bootstrap-timepicker-hour DOUBLE txt_input vitalinputs" readonly style="margin-top:3px; width:45px; background-color: #ffffff;" maxlength="2" type="text">
																            </td>
															
																            <td><a class="valuechanger" href="#" onclick="incrementValue('#vital<s:property value='#rowIndex.index'/>')"><i class="icon-chevron-right"></i></a>
																            </td>
																            
																        </tr>
																    </tbody>
																</table>
															</div>
															
															<td>
																<a onclick="getDefaultValue('#vital<s:property value='#rowIndex.index'/>')">
																	<img src="../theme/img/setdefault.png" class="btn vitalbtn valuechanger">
																</a>
															</td>
															
															
														<s:hidden name="ansTxtDoubleHidden"
															value="%{itemGroupName}" />

													</s:elseif> <s:elseif test="%{itemType.equals('STEXT')}">
														<s:textfield name="ansTxtSText" cssClass="txt_input"
															value="%{recordItemState.selectedList}" />
														<s:hidden name="ansTxtSTextHidden"
															value="%{itemGroupName}" />

													</s:elseif> <s:elseif test="%{itemType.equals('LTEXT')}">
														<s:textarea name="ansTxtLText" cols="40" rows="8"
															cssClass="txt_input" value="%{recordItemState.selectedList}" />
														<s:hidden name="ansTxtLTextHidden"
															value="%{itemGroupName}" />

													</s:elseif>
												</td>
											</tr>
										</s:iterator>
									</table>
								</div>
							</s:form>
						</div>						
					</s:iterator>
					<s:url var="vital_url" namespace="/vital" action="view">
					</s:url>
				</div>
			</div>
		</div>
	</div>
	
	<script type="text/javascript">
		$(document).ready(function() {

			$('input[type="checkbox"]').each(function() {
				var self = $(this), label = self.next(), label_text = label.text();

				label.remove();				
				self.iCheck({
					checkboxClass : 'icheckbox',
					insert : '<div class="icheck-icon"></div>' + label_text
				});
			}); 

			$('input[type="radio"]').each(function() {
				var self = $(this), label = self.next(), label_text = label.text();

				label.remove();
				self.iCheck({
					radioClass : 'iradio',
					insert : '<div class="icheck-icon"></div>' + label_text
				});
			});

			$('#enableTime').iCheck('destroy');
			$('#enableTime').iCheck({
				checkboxClass : 'icheckbox_flat'
			});
			
			
		});
	</script>

	<script type="text/javascript">
		$(document).ready(function() {
			var save_form = false;
			var current_tab = "tab0";			
			
			$(window).bind('beforeunload', function() {
				if (save_form) {
				
					var execDate = $('#datepicker').val();
					$("input[id=executionDate]").val(execDate);
					var frm = $('#' + current_tab).find('form');
					
					$.ajax({
						type : frm.attr('method'),
						url : frm.attr('action'),
						data : frm.serialize(),
						async : false,
						success : function(response) {
							save_form = false;
						},
						error : function(err) {
							alert("suberror" + err);
						}
					});
				}
			});

			$('.iradio').on('ifChanged', function(event) {
				save_form = true;
			});

			$('.icheckbox').on('ifChanged', function(event) {
				save_form = true;
			});

			$('.txt_input').click(function() {
				save_form = true;
			});

			$('.txt_input').keyup(function() {
				save_form = true;
			});
			
			$('.valuechanger').click(function(e){
				save_form = true;
				e.preventDefault();
			});

		/*---------------------------------------------------------*/
			$('#timepicker').attr('disabled', true);
			$('#enableTime').iCheck('uncheck');

			$('#enableTime').on('ifChecked', function(event) {
				$('#timepicker').prop('disabled', false);
				var plannedTime = $('#timepicker').val();
				$("input[id=plannedTime"+current_tab+"]").val(plannedTime);
			});

			$('#enableTime').on('ifUnchecked', function(event) {
				$('#timepicker').prop('disabled', true);
				$('#bootstrap-timepicker-widget').attr("class",	"bootstrap-timepicker-widget dropdown-menu");
				$('#timepicker').blur();
				$("input[id=plannedTime"+current_tab+"]").val(null);
			});

			$('#timepicker').timepicker({
				showMeridian : false,
				minuteStep : 1
			});			
		/*-----------------------------------------------------------*/
		
			var menuitem = '<s:property value="refid" />';

			$('.tab-content').removeClass('hidden');
			$('#menuTab li:eq(0)').removeClass('selected');

			if (menuitem != null && menuitem != "") {
				$('#menuTab li:eq(' + menuitem + ') a').tab('show');
				$.localStorage('tab', 
				$('#menuTab li:eq(' + menuitem + ') a').attr('href'));
				var tab = $('#menuTab li:eq(' + menuitem + ') a').attr('href').substring(1);
				getVitalData(tab);
				
					var $window = $(window);
					var wWidth  = $window.width();
					
					var tabwidth = menuitem*110;
					
					if(tabwidth > wWidth){					
						var diff = wWidth-tabwidth;
						
						var container = $('#sliderTabs').find('div');
						var tabsList = container.children("ul");
						tabsList.animate({'margin-left': diff}, 200);
					}
					showPlanedTime("tab"+menuitem);	

			} else if ($.localStorage('tab') != null) {
				//alert($.localStorage('tab'));
				$("#menuTab a[href$='" + $.localStorage('tab') + "']").tab('show');
				showPlanedTime($.localStorage('tab').split("#")[1]);	
				getVitalData($.localStorage('tab').substring(1));
			} else {
				$('#menuTab a:first').tab('show');
				showPlanedTime("tab0");	
			}

			$('#menuTab a').click(function(e) {
				e.preventDefault();
				$(this).tab('show');
				$.localStorage('tab', $(this).attr('href'));
			});

			$('#menuTab a').on('show',	function(e) {
				var tab = e.target.href.substr(e.target.href.indexOf('#') + 1);
				getVitalData(tab);
			});
			
			$('#menuTab a').on('shown',	function(e) {	
				
				current_tab = e.target.href.substr(e.target.href.indexOf('#') + 1);
				var tab = e.relatedTarget.href.substr(e.relatedTarget.href.indexOf('#') + 1);
				var frm = $('#' + tab).find('form');
								
				showPlanedTime(current_tab);			
				
				if (save_form) {
				
					var execDate = $('#datepicker').val();
					$("input[id=executionDate]").val(execDate);					
					
					$.ajax({
						type : frm.attr('method'),
						url : frm.attr('action'),
						data : frm.serialize(),
						async : false,
						success : function(response) {
							save_form = false;
						},
						error : function(err) {
							alert("error" + eval(err));
						}
					});
				}
			});
			
			function getVitalData(tab) {
				var vital=$('#'+tab).find('input[name="inputGroup"]').val();
				if(vital=='<s:property value="@com.carepad.action.input.RecordItemsInputSaveAction@VITAL_INPUT"/>') {
					$.ajax({
						type : 'POST',
						url : '<s:property value="vital_url"/>',
						dataType : 'html',
						async : false,
						contentType: 'application/json; charset=utf-8',
						success : function(response) {
							//alert(response);
							if(response) {
								var pjson = $.parseJSON(response);
						        $('#vital0').val(pjson.vital0);
						        $('#vital1').val(pjson.vital1);
						        $('#vital2').val(pjson.vital2);
						        $('#vital3').val(pjson.vital3);
							}
							else {
								$('#vital0').val('');
								$('#vital1').val('');
								$('#vital2').val('');
								$('#vital3').val('');
							}
						},
						error : function(err) {
							alert("error" + err);
						}
					});
				}
			}

			function validNumber(code) {
				if (!(code == 8 || code == 46
						|| (code >= 35 && code <= 40)
						|| (code >= 48 && code <= 57) || (code >= 96 && code <= 105))) {
					return false;
				} else {
					return true;
				}
			}

			$('.INTEGER').keydown(function(e) {
				var key = (e.which) ? e.which : e.keyCode;
				if (!validNumber(key)) {
					e.preventDefault();
				}
			});

			$('.DOUBLE').keydown(function(e) {
				var key = (e.which) ? e.which: e.keyCode;
				if (!validNumber(key) && key != 190 && key != 110) {
					e.preventDefault();
				} else {
					if (($(this).val().indexOf(".")) >= 0 && (key == 190 || key == 110)) {
						e.preventDefault();
					}
				}

			});

			$('#btnCurrentTime').click(function() {			
				setCurrentTime();
				$('#enableTime').iCheck('check');
				var plannedTime = $('#timepicker').val();
				$("input[id=plannedTime"+current_tab+"]").val(plannedTime);
			});
			
			function setCurrentTime(){
				var time = new Date();								
				var min = time.getMinutes();
				var hr = time.getHours();
				if(min < 10){ min ='0' + min;}
				if(hr < 10){ hr ='0' + hr;}
				$('#timepicker').prop('value',	hr + ":" + min);
			}
			
			function showPlanedTime(current_tab){
				if (current_tab== null){
					current_tab = "tab0";
				}
				var origplannedTime = $('#' + current_tab).find('#origplannedTime'+ current_tab).val();
					
					if(origplannedTime.length){									
						var splittime = origplannedTime.split(":");					
						$('#timepicker').prop('value',	splittime[0] + ":" + splittime[1]);
						$('#enableTime').iCheck('check');
						$("input[id=plannedTime"+current_tab+"]").val(origplannedTime);
					}
					else{				
						setCurrentTime();
						if(current_tab=="tab2"){
							$('#enableTime').iCheck('check');
						} else {
							$('#enableTime').iCheck('uncheck');
						}
						$("input[id=plannedTime"+current_tab+"]").val(null);
					}
			}

			$('#btnComplete').click(function() {

				var name = '<s:property value="%{#session.CURRENT_PATIENT.userName}"/>';
			    var heading = name +" " +'<s:text name="global.Session.Complete.Title" />';
			    var question = '<s:text name="global.Session.Complete.Quection" />';
			    var cancelButtonTxt = '<s:text name="global.Session.Complete.Cancel" />';;
			    var okButtonTxt = '<s:text name="global.Session.Complete.Confirm" />';;
				var frm = $('#' + current_tab).find('form');
				
			    var callback = function() {
			      if (frm) {
						if (save_form) {
							var execDate = $('#datepicker').val();
							$("input[id=executionDate]").val(execDate);
							
							$.ajax({
								type : frm.attr('method'),
								url : frm.attr('action'),
								data : frm.serialize(),
								async : false,
								success : function(response) {
									save_form = false;
								},
								error : function(err) {
									alert("error" + eval(err));
								}
							});
						}
					}
					window.location = $('#completeSession').attr("href");
					
			    };
			
			    confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);

			});
			
			
 			$('#timepicker').change(function () {
				var plannedTime = $('#timepicker').val();
				$("input[id=plannedTime"+current_tab+"]").val(plannedTime);
			});
			
		});
		
					
		
		var slider = $("div#sliderTabs").sliderTabs();
		/* $('#menuTab').attr("style",	"margin-left: -277px; width: 1446px;");	 */
		
		
		function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {
		    var confirmModal = 
		      $('<div class="modal hide fade">' +    
		          '<div class="modal-header">' +
		            '<a class="close" data-dismiss="modal" >&times;</a>' +
		            '<h4>' + heading +'</h4>' +
		          '</div>' +
		
		          '<div class="modal-body">' +
		            '<p>' + question + '</p>' +
		          '</div>' +
		
		          '<div class="modal-footer">' +
		            '<a href="#" class="btn" data-dismiss="modal">' + 
		              cancelButtonTxt + 
		            '</a>' +
		            '<a href="#" id="okButton" class="btn btn-primary">' + 
		              okButtonTxt + 
		            '</a>' +
		          '</div>' +
		        '</div>');
		
		    confirmModal.find('#okButton').click(function(event) {
		      callback();
		      confirmModal.modal('hide');
		    });
		
		    confirmModal.modal('show');     
		  };
		
		
	</script>
	
	<s:include value="/WEB-INF/content/common/footer.jsp" />